﻿using Net.Server;
using Net.AOI;
using Net.Share;
using System.Collections.Generic;
using Net.Component;
using Net.Event;
using Net.System;
using Example1;
using Net;
using Net.Common;

namespace AOIExample
{
    internal class Scene : SceneBase<Client>
    {
        internal ActorSystem.Scene scene = new();
        public int spawnAmount = 100000;
        public float interleave = 5;

        public Scene()
        {
            scene.AOI.Init(-1000, -1000, 100, 100, 20, 20);
            float sqrt = Mathf.Sqrt(spawnAmount);
            float offset = -sqrt / 2 * interleave;
            int spawned = 0;
            for (int spawnX = 0; spawnX < sqrt; ++spawnX)
            {
                for (int spawnZ = 0; spawnZ < sqrt; ++spawnZ)
                {
                    if (spawned < spawnAmount)
                    {
                        var robot = new Robot();

                        float x = offset + spawnX * interleave;
                        float z = offset + spawnZ * interleave;
                        robot.transform.Position = new Vector3(x, 0, z);
                        ++spawned;

                        scene.AddActor(robot);
                    }
                }
            }
        }
        public override void OnEnter(Client client)
        {
            var player = new Player
            {
                Identity = client.UserId,
                MainRole = true,
                scene = this,
                client = client,
            };
            player.Position = new Vector3(RandomHelper.Range(-20, 20), 1, RandomHelper.Range(-20, 20));
            scene.AddActor(player);
            player.OnEnter(player);
        }
        public override void OnExit(Client client)
        {
            if (Count <= 0) //如果没人时要清除操作数据，不然下次进来会直接发送Command.OnPlayerExit指令给客户端，导致客户端的对象被销毁
                operations.Clear();
            else
                AddOperation(new Operation(OperCommand.OnPlayerExit, client.UserId));
            scene.RemoveActor(client.UserId);
        }
        public override void OnOperationSync(Client client, in OperationList list)
        {
            scene.Dispatch(list);
        }
        public override void Update()
        {
            if (Clients.Count <= 0)
                return;
            scene.Update();
            SendOperitions(operations); //不管aoi, 整个场景的同步在这里, 如玩家退出操作
            Frame++;
        }
    }
}